'use strict';

stareal
    .controller("Venus360Controller", function ($scope,$interval,$document, $stateParams, $api, $sce, base64, $state, $alert,localStorageService,$timeout) {
        $scope.Img=localStorageService.get('360Img');
        $scope.venus360Id=localStorageService.get('venus360Id');
        $alert.show('全景图加载中，请稍等.....');
     //  var height=(document.body.clientHeight-parseInt(document.documentElement.style.fontSize)*1.4)+'px';
       $scope.alert=function(){
           $alert.show('歼击机');
       }
        // function loadPredefinedPanorama() {
        //     var div = document.getElementById('360container');
        //     var PSV = new PhotoSphereViewer({
        //         panorama:$scope.Img,
        //         container: div,
        //         time_anim: false,
        //         navbar: true,
        //         size: {
        //             width: '100%',
        //             height: height
        //         }
        //     });
        // }
        // // window.onload=function(){
        //     loadPredefinedPanorama();
        // }
        var camera,//摄像机
            scene,//舞台
            renderer,//渲染器
            isUserInteracting = false,//用户是否正在操作
            onMouseDownMouseX = 0, onMouseDownMouseY = 0,//鼠标点击的x和Y坐标
            lon = 0, onMouseDownLon = 0, onPointerDownLon= 0.0,onPointerDownPointerX = 0,//经度
            lat = 0, onMouseDownLat = 0, onPointerDownLat= 0.0,onPointerDownPointerY = 0,//纬度
            phi = 0, theta = 0,//计算相机位置的重要参数
            o = new Orienter(),//陀螺仪方法对象
            new_longitude=0,last_longitude=0,move_longitude=0,//改变的经度的计算
            new_latitude=0,last_latitude=0,move_latitude=0,//改变的纬度的计算
            is_touch=false,is_start=false,isPlay=true,isMusicPlay=true,tsa=100.1,ppl='';

        var raycaster = new THREE.Raycaster();//拾取场景里面的物体,可判断点击或交互事件对应的元素
        var mouse = new THREE.Vector2();//二维向量的对象，鼠标计算

        function init(){/**初始化**/
        var container, mesh;//容器和素材
            container = document.getElementById( '360container' );//容器
            camera = new THREE.PerspectiveCamera( 72, window.innerWidth / window.innerHeight, 0.01, 1100 );//相机
            camera.target = new THREE.Vector3( 0, 0, 0 );//相机位置

            scene = new THREE.Scene();//舞台
            scene.updateMatrixWorld(true);
            var geometry = new THREE.SphereGeometry(1, 32, 16);//球体

            geometry.scale( 1, 1, -1 );
            //设置球体的背景贴图
            var textureBg = new THREE.TextureLoader().load( $scope.Img);
            textureBg.generateMipmaps = true;
            textureBg.magFilter = THREE.LinearFilter;//设置贴纸素材的质量
            textureBg.minFilter = THREE.LinearFilter;
            var material = new THREE.MeshBasicMaterial( {
                map: textureBg,//圆柱体贴图，全景图
                //color:0xFF0000,
                //transparent: true
            } );
            mesh = new THREE.Mesh( geometry, material );
            //这里可以设置对应的动画效果
      new TWEEN.Tween( mesh).to( {transform:"rotate(90deg)"}, 800 ).repeat( false ).delay( 300 ).yoyo( true ).easing( TWEEN.Easing.Cubic.InOut ).start();
            scene.add( mesh );

            // 旋转预设 摄影机看到的角度 Start//
            scene.rotation.set(0,0,0); //首頁

            //初始化渲染器，追加到容器
            renderer = new THREE.WebGLRenderer({precision: 'highp' ,mipmap: 'highp',antialias:false});//加上precision 和 mipmap参数，调整画面清晰度
            renderer.setPixelRatio( window.devicePixelRatio );//设置像素比
            renderer.setSize( window.innerWidth, window.innerHeight );//设置渲染窗口的大小
            container.appendChild( renderer.domElement );//追加到容器中去
            var containertouch=document.getElementById('360container')
            //鼠标、手机touch的各个事件
            containertouch.addEventListener( 'mousedown', onDocumentMouseDown, false );
            containertouch.addEventListener( 'mousemove', onDocumentMouseMove, false );
            containertouch.addEventListener( 'mouseup', onDocumentMouseUp, false );

            containertouch.addEventListener( 'touchstart', onDocumentTouchDown, false );
            containertouch.addEventListener( 'touchmove', onDocumentTouchMove, false );
            containertouch.addEventListener( 'touchend', onDocumentTouchUp, false );
            // document.addEventListener( 'wheel', onDocumentMouseWheel, false );
            //
            containertouch.addEventListener( 'dragover', function ( event ) {
                event.preventDefault();
                event.dataTransfer.dropEffect = 'copy';
            }, false );
            containertouch.addEventListener( 'dragenter', function ( event ) {
                document.body.style.opacity = 0.5;
            }, false );
            containertouch.addEventListener( 'dragleave', function ( event ) {
                document.body.style.opacity = 1;
            }, false );
            containertouch.addEventListener( 'drop', function ( event ) {
                event.preventDefault();
                var reader = new FileReader();
                reader.addEventListener( 'load', function ( event ) {
                    material.map.image.src = event.target.result;
                    material.map.needsUpdate = true;
                }, false );
                reader.readAsDataURL( event.dataTransfer.files[ 0 ] );
                document.body.style.opacity = 1;
            }, false );
        }
        //监听横竖屏重新设置尺寸
        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize( window.innerWidth, window.innerHeight );
        }
        function onDocumentMouseDown( event ) {
            event.preventDefault();
            isUserInteracting = true;
            onPointerDownPointerX = event.clientX;
            onPointerDownPointerY = event.clientY;
            onPointerDownLon = lon;
            onPointerDownLat = lat;

            // Click action
            mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
            mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
            raycaster.setFromCamera( mouse, camera );
            var intersects = raycaster.intersectObjects( scene.children );//第一个是最上面一层的元素
           // console.log("点击的元素",intersects);
            if ( intersects.length > 0 ) {//如果点到小圆点 就执行回调函数回调函数为goto_p
                try {
                    intersects[0].object.callback();
                }
                catch(err) {}
            }
        }
        function onDocumentMouseMove( event ) {
            if ( isUserInteracting === true ) {
                lon = ( onPointerDownPointerX - event.clientX ) * 0.1 + onPointerDownLon;
                lat = ( event.clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat;
            }
        }
        function onDocumentMouseUp( event ) {
            isUserInteracting = false;
        }

        //  touch event start
        function onDocumentTouchDown( event ) {
            is_touch=true;

            event.preventDefault();
            isUserInteracting = true;
            onPointerDownPointerX = event.touches[ 0 ].clientX;
            onPointerDownPointerY = event.touches[ 0 ].clientY;
            if(is_start){
                onPointerDownLon = lon;
                onPointerDownLat = lat;
            }
            // For Click action

            mouse.x = ( onPointerDownPointerX / renderer.domElement.clientWidth ) * 2 - 1;
            mouse.y = - ( onPointerDownPointerY / renderer.domElement.clientHeight ) * 2 + 1;

            raycaster.setFromCamera( mouse, camera );
            var intersects = raycaster.intersectObjects( scene.children );
            // console.log('touchDown',lon,lat);
            if ( intersects.length > 0 ) {
                try {
                    intersects[0].object.callback();
                }
                catch(err) {}
            }
        }
        function onDocumentTouchMove( event ) {
            if(is_start){
                if ( isUserInteracting === true ) {

                    lon = ( onPointerDownPointerX - event.touches[ 0 ].clientX ) * 0.1 + onPointerDownLon;
                    lat = ( event.touches[ 0 ].clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat;
                }
            }
        }
        function onDocumentTouchUp( event ) {
            is_touch=false;
        }
        //  touch event end

        //  set
        function onDocumentTouchDown2( event ) {
            tsa = event.touches[0].clientY;
            // console.log( '@:'+event.touches[0].clientY );
            event.preventDefault();

        }
        function onDocumentMouseWheel( event ) {
            camera.fov += event.deltaY * 0.05;
            camera.updateProjectionMatrix();
        }
        function animate() {//播放动画
            if(isPlay){
                TWEEN.update();
                update();
                requestAnimationFrame( animate );
            }

        }
        o.onOrient = function (obj) {//重力感应计算角度
            if(is_start){
                //最新经度
                new_longitude = obj.lon;
                move_longitude=new_longitude-last_longitude;

                //最新纬度
                new_latitude = obj.lat;
                move_latitude = new_latitude-last_latitude;

                //判断经纬度
                if(move_longitude>=300){
                    move_longitude=move_longitude-361;
                }else if(move_longitude<=-300){
                    move_longitude=move_longitude+359;
                }


                if(move_latitude>=300){
                    move_latitude=move_latitude-361;
                }else if(move_latitude<=-300){
                    move_latitude=move_latitude+359;
                }

                if( is_touch ){
                    move_longitude=0;
                    move_latitude=0;
                }else{
                    move_longitude=move_longitude*0.6;
                    move_latitude=move_latitude*0.6;
                }
                //计算得出重力感应的经纬度
                lon=lon-move_longitude;
                last_longitude = obj.lon;
                lat = lat-move_latitude;
                last_latitude = obj.lat;
            }

        };

        function update() {//更新摄像机位置，旋转平移
            //lat = Math.max( -6, Math.min( 6, lat ) );//设置lat纬度的范围，只在一个范围内旋转
            phi = THREE.Math.degToRad( 90 - lat );
            theta = THREE.Math.degToRad( lon );
            camera.target.x =  500 * Math.sin( phi ) * Math.cos( theta );//X轴的坐标
            camera.target.y = 500 * Math.cos( phi );//y轴的坐标
            camera.target.z =  500 * Math.sin( phi ) * Math.sin( theta ) ;//z轴的坐标
            camera.lookAt( camera.target );
            renderer.render( scene, camera );//重新渲染
        }
        //执行所有
        is_start=true;
        init();
        o.init();
        animate();

    });